<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品模型
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityWorks extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_works';


    /*关联打卡信息*/
    public function conCompetiteActivity()
    {
        return $this->hasOne(CompetiteActivity::class, 'id', 'con_id');
    }

    /**
     * 关联作品类型
     */
    public function conType()
    {
        return $this->hasOne(CompetiteActivityWorksType::class, 'id', 'type_id');
    }
    /*关联审核情况*/
    public function conCheck()
    {
        return $this->belongsToMany(Manage::class, CompetiteActivityWorksCheck::class, 'works_id', 'check_manage_id');
    }
    /**
     * 获取总投票量
     * @param con_id 大赛id
     */
    public function getTotalVoteNumber($con_id)
    {
        return $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->where('status', 1)->sum('vote_num');
    }


    /**
     * 获取作品编号
     * @param  letter 作品编号
     */
    public function getSerialNumber($letter)
    {
        for ($i = 1; $i < 10; $i++) {
            $serial_number = $letter . get_rnd_number(8);

            $is_exists = $this->where('serial_number', $serial_number)->first();

            if (!$is_exists) {
                return $serial_number;
            }
            continue;
        }

        throw new \Exception('条形码获取有误，请联系管理员处理'); //获取10次都获取不到，就不在获取
    }


    /**
     * 获取未查看个数
     */
    public function getUnLookNumber($con_id)
    {
        return $this->where('con_id', $con_id)->where('is_look', 2)->count();
    }

    /**
     * 获取未审核个数
     */
    public function getUnCheckNumber($con_id)
    {
        return $this->where('con_id', $con_id)->where('status', 3)->where('is_violate', 1)->count(); //违规后就可以不用审核了
    }


    /**
     * 获取参与人数
     */
    public function getTakeNumber($con_id)
    {
        $res =  $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->whereIn('status', [1, 2, 3])
            ->where('type', 1)
            ->groupBy('user_id')
            ->get()
            ->toArray(); //分组后调用 聚合函数数据不正常，因为分组后，数据是按照分组返回，调用 count，只会返回一条数据

        $res2 =  $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->whereIn('status', [1, 2, 3])
            ->where('type', 2)
            ->groupBy('group_id')
            ->get()
            ->toArray(); //分组后调用 聚合函数数据不正常，因为分组后，数据是按照分组返回，调用 count，只会返回一条数据
        return count($res) + count($res2); //用户人数+团队人数
    }
    /**
     * 获取作品数量
     */
    public function getWorksNumber($con_id)
    {
        return $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->whereIn('status', [1, 2, 3])->count();
    }

    /**
     * 判断某个活动是否有人报名
     */
    public function actIsApply($id)
    {
        $apply_status = $this->where('con_id', $id)->whereIn('status', [1, 3])->first();
        return $apply_status ? true : false;
    }



    /**
     * 判断是否有人投票
     */
    public function actIsVote($id)
    {
        $vote_num = $this->where('con_id', $id)->sum('vote_num');
        return $vote_num ? true : false;
    }

    /**
     * 参赛作品列表
     * @param type 类型  1 个人账号  2 团队账号  当前是团队查询还是个人查询
     * @param con_id id
     * @param group_id 大赛团队id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type_id int 类型id
     * @param user_id int 用户id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序  3 评分排序
     * @param status int 状态  1.已通过   2.未通过   3.未审核(默认)  4.已撤销， 6.已违规  数组形式或逗号拼接形式
     * @param keywords string 搜索关键词(名称)
     * @param except_ids string 需要排除的id ，多个逗号链接
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param is_review_score string 是否评审打分  1 已打分  2 未打分
     * @param is_add_ebook string 是否是加入电子书 1 是 
     * @param is_violate string 是否违规  1正常 2违规 
     * @param is_show string 是否显示  1显示 2不显示 
     * @param except_database_id string 排除数据库对应产品id
     * 
     * 
     * @param score_manage_id string 打分审核人id  （con_id 必须存在）
     * @param score_manage_status string 打分审核人选择状态  0 查询所有（不排除掉其他管理员已选择的） 1 查看所有已选择的作品  2 查询所有未选中的作品 
     */
    public function lists($con_id, $type = null, $group_id = null, $user_id = null, $type_id = null, $keywords = null, $status = ['1'], $except_ids = '', $is_review_score = null, $is_add_ebook = null, $is_violate = null, $is_show = null, $start_time = null, $end_time = null, $sort = 'id DESC', $except_database_id = null, $score_manage_id = null, $score_manage_status = null, $limit = null)
    {
        if (empty($field)) {
            $field = [
                'id', 'con_id', 'group_id', 'type_id', 'type', 'group_id', 'user_id', 'serial_number', 'cover', 'width', 'height', 'title', 'browse_num',
                'vote_num', 'status', 'create_time', 'is_look', 'is_violate', 'violate_reason', 'violate_time', 'content', 'voice', 'video', 'img', 'review_score', 'average_score',
                'next_check_manage_id', 'next_score_manage_id', 'pdf_works_address', 'authorizations_address', 'promise_address', 'is_show', 'score', 'username', 'tel', 'id_card', 'wechat_number',
                'adviser', 'adviser_tel', 'unit', 'reader_id', 'age', 'school', 'participant', 'original_work', 'reason'
            ];
        }
        $except_database_works_id = [];
        if ($except_database_id) {
            //获取数据库下面的作品id
            $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
            $except_database_works_id = $competiteActivityWorksDatabaseModel->databaseWorksId($except_database_id, 1);
        }

        $score_manage_works_id_ed = []; //已被自己选择
        if ($score_manage_id && $con_id) {
            $competiteActivityWorksAppointScoreModel = new CompetiteActivityWorksAppointScore();
            $score_manage_works_id_ed = $competiteActivityWorksAppointScoreModel->where('score_manage_id', $score_manage_id)->where('con_id', $con_id)->pluck('works_id')->toarray();
        }

        $res = $this->select($field)
            ->where(function ($query) use ($con_id, $type, $group_id, $user_id, $type_id, $status, $except_ids, $is_review_score, $is_violate, $is_show, $start_time, $end_time) {
                if ($con_id) {
                    $query->where('con_id', $con_id);
                }
                if ($status) {
                    $status = !is_array($status) ? explode(',', $status) : $status;
                    $query->whereIn('status', $status);
                }
                if ($type == 1) {
                    $query->where('type', 1);
                } elseif ($type == 2) {
                    $query->where('type', 2);
                }
                if ($group_id) {
                    $query->where('group_id', $group_id);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }

                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($is_violate) {
                    $query->where('is_violate', $is_violate);
                }
                if ($is_review_score) {
                    if ($is_review_score == 1) {
                        $query->whereNotNull('review_score');
                    } else {
                        $query->whereNull('review_score');
                    }
                }
                if ($except_ids) {
                    $except_ids = explode(',', $except_ids);
                    $query->whereNotIn('id', $except_ids);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
                if ($is_show) {
                    $query->where('is_show', $is_show);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($is_add_ebook) {
                if ($is_add_ebook == 1) {
                    $query->whereNotNull('img')->orWhereNotNull('content'); //只有有一个不是空可以
                }
            })->where(function ($query) use ($is_add_ebook) {
                if ($is_add_ebook == 1) {
                    $query->whereNull('voice')->whereNull('video'); //并且2个都必须是空才可以
                }
            })->where(function ($query) use ($except_database_id, $except_database_works_id) {
                if ($except_database_id && $except_database_works_id) {
                    $query->whereNotIn('id', $except_database_works_id);
                }
            })
            ->where(function ($query) use ($con_id, $score_manage_id, $score_manage_status, $score_manage_works_id_ed) {
                if ($score_manage_id && $con_id) {
                    if ($score_manage_status == 1) {
                        $query->whereIn('id', $score_manage_works_id_ed);
                    } elseif ($score_manage_status == 2) {
                        $query->whereNull('review_score')->whereNotIn('id', $score_manage_works_id_ed); //已经打过分的不能在选择
                    } else {
                        $query->whereNull('review_score')->orWhereIn('id', $score_manage_works_id_ed); //没打过分的，或自己之前已经选择了的
                    }
                }
            })
            ->where('status', '<>', 5);

        $total_vote_num = $res->sum('vote_num');
        $res = $res->orderByRaw($sort)
            ->paginate($limit)
            ->toArray();
        //增加是否投票参数
        $competiteActivityWorksScoreModel = new CompetiteActivityWorksScore();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['appraise_way'] = CompetiteActivity::where('id', $val['con_id'])->value('appraise_way');
            //获取用户的打分情况
            list($res['data'][$key]['works_score_list'], $res['data'][$key]['works_score_string']) = $competiteActivityWorksScoreModel->getWorksScoreList($val['id']);
        }
        $res['total_vote_num'] = $total_vote_num;
        return $res;
    }

    /**
     * 参赛作品打分列表
     * @param type 类型  1 个人账号  2 团队账号  当前是团队查询还是个人查询
     * @param con_id id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(名称)
     * @param is_review_score string 是否评审打分  1 已打分  2 未打分
     * @param score_manage_id string 打分审核人id  默认是自己
     */
    public function scoreLists($con_id, $type = null, $keywords = null, $is_review_score = null, $score_manage_id = null, $limit = null)
    {
        if (empty($field)) {
            $field = [
                'w.id', 'con_id', 'group_id', 'type_id', 'w.type', 'group_id', 'user_id', 'serial_number', 'cover', 'width', 'height', 'title', 'browse_num',
                'vote_num', 'status', 'w.create_time', 'content', 'voice', 'video', 'img', 'pdf_works_address', 'authorizations_address', 'promise_address',
                's.review_score', 's.review_score as sreview_score', 's.change_time'
            ];
        }
        $res = $this->from($this->getTable() . ' as w')->select($field)
            ->join('competite_activity_works_score as s', 's.works_id', '=', 'w.id')
            ->where(function ($query) use ($con_id, $type, $is_review_score) {
                if ($con_id) {
                    $query->where('con_id', $con_id);
                }
                if ($type == 1) {
                    $query->where('w.type', 1);
                } elseif ($type == 2) {
                    $query->where('w.type', 2);
                }

                if ($is_review_score) {
                    if ($is_review_score == 1) {
                        $query->whereNotNull('s.review_score');
                    } else {
                        $query->whereNull('s.review_score');
                    }
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('s.score_manage_id', $score_manage_id)
            ->where('w.status', 1)
            ->orderByRaw('ifnull(sreview_score, "") asc') //优先显示无值的记录
            ->orderBy('w.change_time')
            ->paginate($limit)
            ->toArray();

        return $res;
    }


    /**
     * 获取待审核活动列表
     * @param manage_id
     */
    public function getNotCheckWorksList($manage_id)
    {
        $res = $this->select('con_id', DB::raw("count(con_id) as count"))
            ->where('next_check_manage_id', $manage_id)
            ->where('status', 3)
            ->where('is_violate', 1) //违规后就不能审核了
            ->groupBy('con_id')
            ->get()
            ->toArray();
        $competiteActivityModel = new CompetiteActivity();
        foreach ($res as $key => $val) {
            $res[$key]['title'] = $competiteActivityModel->where('id', $val['con_id'])->value('title');
        }
        return $res;
    }
    /**
     * 获取待打分活动列表
     * @param manage_id
     */
    public function getNotReviewScoreWorksList($manage_id)
    {
        // 获取未打分的作品列表
        $not_score_works_ids = CompetiteActivityWorksScore::where('score_manage_id', $manage_id)->whereNull('review_score')->pluck('works_id');
        $res = $this->select('con_id', DB::raw("count(con_id) as count"))
            ->whereIn('id', $not_score_works_ids)
            ->where('status', 1)
            ->where('is_violate', 1)
            ->groupBy('con_id')
            ->get()
            ->toArray();
        $competiteActivityModel = new CompetiteActivity();
        foreach ($res as $key => $val) {
            $res[$key]['title'] = $competiteActivityModel->where('id', $val['con_id'])->value('title');
        }
        return $res;
    }

    /**
     * 获取作品详情（新）
     * 
     */
    public function scoreDetail($id, $score_manage_id)
    {
        if (empty($field)) {
            $field = [
                'w.id', 'con_id', 'group_id', 'type_id', 'w.type', 'group_id', 'user_id', 'serial_number', 'cover', 'width', 'height', 'title', 'browse_num',
                'vote_num', 'status', 'w.create_time', 'content', 'voice', 'video', 'img', 'pdf_works_address', 'authorizations_address', 'promise_address',
                's.review_score', 's.change_time'
            ];
        }
        $res = $this->from($this->getTable() . ' as w')
            ->select($field)
            ->join('competite_activity_works_score as s', 's.works_id', '=', 'w.id')
            ->where('s.score_manage_id', $score_manage_id)
            ->where('w.status', 1)
            ->where('w.id', $id)
            ->first();
        return $res;
    }

    /**
     * 获取打分作品详细
     * 
     */
    public function detail($id, $field = [], $is_show = null)
    {
        if (empty($field)) {
            $field = [
                'id', 'group_id', 'type', 'con_id', 'user_id', 'serial_number', 'username', 'tel', 'id_card', 'wechat_number',
                'adviser', 'adviser_tel', 'reader_id', 'title', 'type_id', 'img', 'content', 'voice', 'voice_name', 'video', 'video_name',
                'intro', 'cover', 'width', 'height', 'browse_num', 'vote_num', 'status', 'reason', 'create_time', 'change_time',
                'is_violate', 'violate_reason', 'violate_time', 'next_check_manage_id', 'next_score_manage_id',
                'age', 'school', 'participant', 'original_work', 'authorizations_address', 'promise_address', 'is_show', 'pdf_works_address'
            ];
        }
        $res = $this->select($field)
            ->with(['conType' => function ($query) {
                $query->select('id', 'type_name', 'limit_num', 'letter', 'node');
            }, 'conCheck' => function ($query) {
                $query->select('check_manage_id', 'account', 'username', 'status', 'reason', 'competite_activity_works_check.create_time')->where('is_del', 1);
            }])
            ->where(function ($query) use ($is_show) {
                if ($is_show) {
                    $query->where('is_show', $is_show);
                }
            })
            ->where('id', $id)
            ->first();

        return $res;
    }


    /**
     * 获取下一个未审核的作品
     * @param con_id id
     * @param group_id 大赛团队id
     * @param type_id int 类型id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     * @param keywords string 搜索关键词(名称)
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     */
    public function getNextUnchecked($con_id, $group_id, $type_id, $keywords, $start_time, $end_time, $sort, $field = [])
    {
        if (empty($field)) {
            $field = [
                'id', 'group_id', 'con_id', 'user_id', 'serial_number', 'username', 'tel', 'id_card', 'wechat_number',
                'adviser', 'adviser_tel', 'reader_id', 'title', 'type_id', 'img', 'content', 'voice', 'voice_name', 'video', 'video_name',
                'intro', 'cover', 'width', 'height', 'browse_num', 'vote_num', 'status', 'reason', 'create_time', 'change_time',
                'is_violate', 'violate_reason', 'violate_time', 'next_check_manage_id', 'next_score_manage_id', 'type',
                'age', 'school', 'participant', 'original_work', 'authorizations_address', 'promise_address', 'is_show', 'pdf_works_address'
            ];
        }
        $res = $this->select($field)->with([
            'conType' => function ($query) {
                $query->select('id', 'type_name', 'limit_num', 'letter', 'node');
            }, 'conCheck' => function ($query) {
                $query->select('check_manage_id', 'account', 'username', 'status', 'reason', 'competite_activity_works_check.create_time')->where('is_del', 1);
            }
        ])
            ->where(function ($query) use ($group_id, $type_id, $start_time, $end_time) {
                if ($group_id) {
                    $query->where('group_id', $group_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')
                        ->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('con_id', $con_id)
            ->where('is_violate', 1)
            ->where('status', 3)
            ->where('next_check_manage_id', request()->manage_id)
            ->orderByRaw($sort)
            ->first();

        return $res;
    }

    /**
     * 获取下一个未打分的作品
     * @param con_id id
     * @param group_id 大赛团队id
     * @param type_id int 类型id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     * @param keywords string 搜索关键词(名称)
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     */
    public function getNextUnScoreed($con_id, $group_id, $type_id, $keywords, $start_time, $end_time, $sort, $field = [])
    {
        // 获取未打分的作品列表
        $not_score_works_ids = CompetiteActivityWorksScore::where('score_manage_id', request()->manage_id)->whereNull('review_score')->pluck('works_id');
        if (empty($not_score_works_ids)) {
            return [];
        }
        if (empty($field)) {
            $field = [
                'id', 'group_id', 'con_id', 'user_id', 'serial_number', 'username', 'tel', 'id_card', 'wechat_number',
                'adviser', 'adviser_tel', 'reader_id', 'title', 'type_id', 'img', 'content', 'voice', 'voice_name', 'video', 'video_name',
                'intro', 'cover', 'width', 'height', 'browse_num', 'vote_num', 'status', 'reason', 'create_time', 'change_time',
                'is_violate', 'violate_reason', 'violate_time', 'next_check_manage_id', 'next_score_manage_id', 'type',
                'age', 'school', 'participant', 'original_work', 'authorizations_address', 'promise_address', 'is_show', 'pdf_works_address'
            ];
        }
        $res = $this->select($field)->with([
            'conType' => function ($query) {
                $query->select('id', 'type_name', 'limit_num', 'letter', 'node');
            }, 'conCheck' => function ($query) {
                $query->select('check_manage_id', 'account', 'username', 'status', 'reason', 'competite_activity_works_check.create_time')->where('is_del', 1);
            }
        ])
            ->where(function ($query) use ($group_id, $type_id, $start_time, $end_time) {
                if ($group_id) {
                    $query->where('group_id', $group_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')
                        ->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('con_id', $con_id)
            ->where('status', 1)
            ->where('is_violate', 1)
            ->whereIn('id', $not_score_works_ids)
            ->orderByRaw($sort)
            ->first();

        return $res;
    }


    /**
     * 获取作品详情（新）
     * 
     */
    public function getNextUnScoreWorks($con_id, $type = null, $keywords = null, $score_manage_id = null)
    {
        if (empty($field)) {
            $field = [
                'w.id', 'con_id', 'group_id', 'type_id', 'w.type', 'group_id', 'user_id', 'serial_number', 'cover', 'width', 'height', 'title', 'browse_num',
                'vote_num', 'status', 'w.create_time', 'content', 'voice', 'video', 'img', 'pdf_works_address', 'authorizations_address', 'promise_address',
                's.review_score', 's.change_time', 'is_show'
            ];
        }
        $res = $this->from($this->getTable() . ' as w')
            ->select($field)
            ->join('competite_activity_works_score as s', 's.works_id', '=', 'w.id')
            ->where(function ($query) use ($con_id, $type) {
                if ($con_id) {
                    $query->where('con_id', $con_id);
                }
                if ($type == 1) {
                    $query->where('w.type', 1);
                } elseif ($type == 2) {
                    $query->where('w.type', 2);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->whereNull('s.review_score')
            ->where('s.score_manage_id', $score_manage_id)
            ->where('w.status', 1)
            ->first();

        if (isset($res['review_score'])) {
            $res['review_score_status'] == 1; //已打分
        } else {
            $res['review_score_status'] == 3; //待打分
        }

        return $res;
    }



    /**
     * 计算某个类型，某个用户上传的作品数量，超过限制，不允许在继续上传
     * @param user_id 用户id
     * @param type_id 类型id
     */
    public function getUserWorksNumberByTypeId($con_id, $type, $group_id, $user_id, $type_id)
    {
        return $this->where('con_id', $con_id)
            ->where(function ($query) use ($type, $group_id, $user_id) {
                if ($type == 1) {
                    $query->where('type', 1);
                } elseif ($type == 2) {
                    $query->where('type', 2);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
                if ($group_id) {
                    $query->where('group_id', $group_id);
                }
            })
            ->where('type_id', $type_id)
            ->whereIn('status', [1, 2, 3, 4])
            ->count();
    }

    /**
     * 处理数据数据
     */
    public function disData($data, $pdf_title)
    {
        $path_arr = [];
        $pdfObj = new PdfController();
        //保存文字转换为PDF格式
        if ($data['content']) {
            $pdf_path = $pdfObj->setPdf(
                $pdf_title,
                ['<h2 style="text-align: center">' . $data['title'] . '</h1><div>' . $data['content'] . '</div>'],
                null,
                $data['serial_number']
            );
            $path_arr['pdf_path'] = $pdf_path;
            $path_arr['pdf_name'] = $data['serial_number'] . '-文字作品.pdf';
        } else {
            $path_arr['pdf_path'] = null;
            $path_arr['pdf_name'] = null;
        }
        if ($data['voice']) {
            $path_arr['voice_path'] = $data['voice'];
            $voice_name = explode('.', $data['voice']);
            $path_arr['voice_name'] = $data['serial_number'] . '.' . end($voice_name);
        } else {
            $path_arr['voice_path'] = null;
            $path_arr['voice_name'] = null;
        }
        if ($data['video']) {
            $path_arr['video_path'] = $data['video'];
            $video_name = explode('.', $data['video']);
            $path_arr['video_name'] = $data['serial_number'] . '.' . end($video_name);
        } else {
            $path_arr['video_path'] = null;
            $path_arr['video_name'] = null;
        }
        if ($data['img']) {
            $path_arr['img_path'] = $data['img'];
            $img_name = explode('.', $data['img']);
            $path_arr['img_name'] = $data['serial_number'] . '-图片作品.' . end($img_name);
        } else {
            $path_arr['img_path'] = null;
            $path_arr['img_name'] = null;
        }
        //pdf作品
        if ($data['pdf_works_address']) {
            $path_arr['pdf_works_path'] = $data['pdf_works_address'];
            $img_name = explode('.', $data['pdf_works_address']);
            $path_arr['pdf_works_name'] = $data['serial_number'] . '-PDF作品.' . end($img_name);
        } else {
            $path_arr['pdf_works_path'] = null;
            $path_arr['pdf_works_name'] = null;
        }
        //授权书
        if ($data['authorizations_address']) {
            $path_arr['authorizations_path'] = $data['authorizations_address'];
            $img_name = explode('.', $data['authorizations_address']);
            $path_arr['authorizations_name'] = $data['serial_number'] . '-授权书.' . end($img_name);
        } else {
            $path_arr['authorizations_path'] = null;
            $path_arr['authorizations_name'] = null;
        }
        //承诺书
        if ($data['promise_address']) {
            $path_arr['promise_path'] = $data['promise_address'];
            $img_name = explode('.', $data['promise_address']);
            $path_arr['promise_name'] = $data['serial_number'] . '-承诺书.' . end($img_name);
        } else {
            $path_arr['promise_path'] = null;
            $path_arr['promise_name'] = null;
        }
        return $path_arr;
    }


    /**
     * 判断当前作品是否是自己审核
     * @param $works_id 作品id
     */
    public function getSelfCheckStatus($works_id, $works_info = null, $manage_id = null)
    {
        if (empty($manage_id)) {
            $manage_id = request()->manage_id;
        }
        if (empty($works_info)) {
            $works_info = $this->where('id', $works_id)->first();
        }
        if ($works_info['is_violate'] == 2) {
            return 6; //已违规，不允许审核了
        }
        if ($works_info['status'] == 1 || $works_info['status'] == 2) {
            return $works_info['status']; //总状态 已审核 则其余的不需要在查询了    1.已通过   2.未通过
        }
        //获取所有的审核人
        $check_info = CompetiteActivityWorksCheck::select('check_manage_id', 'status')->where('works_id', $works_id)->get()->toArray();
        $check_manage_id_all = CompetiteActivity::where('id', $works_info['con_id'])->value('check_manage_id');
        $check_manage_id_all = explode(',', $check_manage_id_all);
        $check_manage_id_status = array_column($check_info, 'status', 'check_manage_id');
        if (!in_array($manage_id, $check_manage_id_all)) {
            return 5; //无审核权限
        }
        if (isset($check_manage_id_status[$manage_id]) && ($check_manage_id_status[$manage_id] != 1 || $check_manage_id_status[$manage_id] != 2)) {
            return $check_manage_id_status[$manage_id]; //已审核 状态    1.已通过   2.未通过
        }
        if ($works_info['next_check_manage_id'] == $manage_id) {
            return 3; //待审核，自己审核了
        }
        return 4; //不是自己审核
    }

    /**
     * 判断当前作品是否是自己打分
     * @param $works_id 作品id 
     * @param manage_id 管理员id
     */
    public function getSelfReviewScoreStatus($works_id, $works_info = null, $manage_id = null)
    {
        if (empty($manage_id)) {
            $manage_id = request()->manage_id;
        }
        if (empty($works_info)) {
            $works_info = $this->where('id', $works_id)->first();
        }
        if ($works_info['is_violate'] == 2 || $works_info['status'] != 1) {
            return 6; //已违规或不是审核通过状态，不允许打分
        }

        //获取所有的打分人,目前只有一个打分人
        // $score_manage_id = CompetiteActivityWorksType::where('id', $works_info['type_id'])->where('con_id', $works_info['con_id'])->where('is_del', 1)->value('score_manage_id');

        $score_works_status = CompetiteActivityWorksScore::where('score_manage_id', request()->manage_id)->where('works_id', $works_id)->first();
        if (empty($score_works_status)) {
            return 5; //无打分权限
        }
        if ($score_works_status && $score_works_status['review_score'] === null) {
            return 3; //待打分
        }

        return 1; //已打分
    }

    /**
     * 修改为下一个审核管理员(只修改未审核完成的作品)
     * @param con_id  大赛id
     * @param manage_id  当前审核人
     */
    public function changeWorksCheckManage($con_id, $works_id, $manage_id)
    {
        $competiteActivityWorksCheckModel = new CompetiteActivityWorksCheck();
        //获取下一个审批管理员
        $check_manage_id = $competiteActivityWorksCheckModel->getNextCheckManageId($con_id, $works_id, $manage_id);
        if ($check_manage_id === false) {
            return false; //不做任何更改
        }

        //$this->where('id' , $works_id)->where('con_id', $con_id)->where('status', 3)->where('next_check_manage_id', '<>', $check_manage_id)->update(['next_check_manage_id' => $check_manage_id]);
        $this->where('id', $works_id)->where('con_id', $con_id)->where('status', 3)->update(['next_check_manage_id' => $check_manage_id]);
        return $check_manage_id;
    }

    /**
     * 判断当前作品是否只包含文字和图片
     * @param works_id 作品id
     */
    public function isCanAddEbook($works_id)
    {
        $res = $this->where('id', $works_id)->where('is_violate', 1)->where('status', 1)->first();
        if (empty($res)) {
            return '作品不存在，不允许添加入电子书';
        }
        if (!empty($res['voice']) || !empty($res['video'])) {
            return "作品“" . $res['title'] . '”包含视频和音频，不允许添加入电子书';
        }
        if (empty($res['content']) && empty($res['img'])) {
            return "作品“" . $res['title'] . '”无任何内容，不允许添加入电子书';
        }
        return $res->toArray();;
    }

    /**
     * 获取用户参数征集活动次数
     * @param user_id 用户id 
     */
    public function getUserApplyNumber($user_id)
    {
        $res = $this->where('user_id', $user_id)->whereIn('status', [1, 2, 3])->groupBy('con_id')->get();
        return count($res);
    }

    /**
     * 活动类型统计数据
     * @param $user_id 用户id
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     */
    public function userApplyTypeStatistics($user_id = null)
    {
        $res = $this->from($this->getTable() . ' as p')
            ->join('competite_activity as a', 'a.id', '=', 'p.con_id')
            ->join('competite_activity_type as t', 't.id', '=', 'a.type_id')
            ->select("a.type_id", 't.type_name', DB::raw("count(" . config('database.connections.mysql.prefix') . "a.type_id) as count"))
            ->where(function ($query) use ($user_id) {
                if ($user_id) {
                    $query->where('p.user_id', $user_id);
                }
            })->whereIn('status', [1, 2, 3])
            ->orderByDesc('count')
            ->groupBy('type_id')
            ->get()
            ->toArray();
        return $res;
    }


    /**
     * 是否可以一键拒绝
     */
    public function isRefuseDirectly($data)
    {
        if ($data['status'] != 1 && $data['status'] != 3) {
            return false; //不能一键拒绝
        }
        return true;
    }
}
